<!-- 账号权限 -->
<template>
  <SearchTable :query="data.query" :list="data.list" :total="data.total" :showForm="false" @changeSize="changeSize"
    @changePage="changePage" @search="getSearchList" @changeTh="data.dialogVisible = true" @reset="onHideDetails">
    <template #form></template>
    <template #button>
      <el-button type="primary" @click="add">新增角色</el-button>
    </template>
    <template #table>
      <template v-for="(item, index) in data.fields" :key="index">
        <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width">
          <template #header>
            <el-tooltip v-if="item.tips" effect="dark" placement="top">
              <template #content> {{ item.tips }} </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            {{ item.label }}
          </template>
          <template v-if="item.prop == 'role_name'" #default="scope">
            【{{ scope.row.id }}】{{ scope.row.role_name }}
          </template>
          <template v-if="item.prop == 'create_at'" #default="scope">
            {{ setTimestampTime(scope.row.create_at) }}
          </template>
        </el-table-column>
      </template>
      <el-table-column fixed="right" label="操作" width="150">
        <template #header>
          <el-tooltip effect="dark" placement="top">
            <template #content> 删除：删除角色会把此角色下的后台账号一并删除 <br />编辑：重新编辑此角色菜单权限，名称 </template>
            <el-icon class="ques-tips">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
          详情
        </template>
        <template #default="scope">
          <el-button type="primary" v-permiss="'/system/destroyManager'" size="small"
            @click="checkDetails(scope.row, 'edit')">
            编 辑
          </el-button>
          <el-button type="danger" v-permiss="'/system/destroyManager'" size="small"
            @click="checkDetails(scope.row, 'delete')">
            删 除
          </el-button>
        </template>
      </el-table-column>
    </template>
  </SearchTable>

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
    @resetData="resetData"></tableHeader>

  <!-- 新增 -->
  <el-dialog v-model="data.isShowDetails" :title="data.dialogTitle" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form :model="data.formParams" ref="formParams" :rules="data.rules" status-icon label-width="120">
      <el-form-item label="角色名称：" prop="role_name">
        <el-input v-model="data.formParams.role_name" />
      </el-form-item>
      <el-form-item label="角色权限：" class="tree-form">
        <el-tree ref="treeRef" :data="data.treeList" show-checkbox node-key="id" default-expand-all highlight-current
          :props="data.defaultProps" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.isShowDetails = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs, onMounted, computed, watch, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox, ElTree } from 'element-plus'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import {
  getGeneralRoleList,
  addGeneralRole,
  editGeneralRole,
  deleteGeneralRole,
  getPermissionList
} from '@/api/account'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import { setTimestampTime } from '@/utils/time'
import { useStore } from '@/stores/index'
const indexStore = useStore()

const data = reactive({
  query: {
    page: 1,
    size: 50,
  },
  list: [],
  total: 0,
  fields: [
    { label: '角色名称', prop: 'role_name', width: '', visible: true, tips: '后台账号的角色名称，便于后台账号权限分类' },
    { label: '创建时间', prop: 'create_at', width: '', visible: true, tips: '此角色创建时间' }
  ],
  dialogVisible: false,
  treeList: [],
  isShowDetails: false,
  dialogTitle: '新增角色',
  formParams: {
    id: 0,
    role_name: '',
    permissions: '',
    status: 1
  },
  defaultProps: {
    children: 'children',
    label: 'title'
  },
  defaultCheckedKeys: [],
  rules: {
    role_name: [{ required: true, message: '请输入', trigger: 'blur' }]
  },
  pidList: ['3', '4', '5', '6', '7', '8', '9', '10']
})

watch(
  () => data.isShowDetails,
  async (val) => {
    if (val) {
      if (!data.treeList.length) {
        let res = await getPermissionList({})
        data.treeList = res.data
      }
    }
  }
)
onMounted(async () => {
  getSearchList()
})

const getSearchList = async () => {
  indexStore.setPageLoading(true)
  let res = await getGeneralRoleList(data.query)
  indexStore.setPageLoading(false)
  data.list = res.data.list
  data.total = res.data.total
}

const formParams = ref<FormInstance>()
const treeRef = ref<InstanceType<typeof ElTree>>()

const add = async () => {
  data.dialogTitle = '新增角色'
  data.isShowDetails = true
  if (!formParams) return
  formParams.value?.resetFields()
  data.formParams.id = 0
  data.formParams.permissions = ''
  treeRef.value && treeRef.value!.setCheckedKeys([], false)
}

const checkDetails = (row: any, type: string) => {
  if (type == 'edit') {
    nextTick(() => {
      data.dialogTitle = '编辑角色'
      data.isShowDetails = true
    }).then(() => {
      data.formParams = Object.assign(data.formParams, row)
      let checkList = row.permissions.length ? row.permissions.split(',') : [],
        oldList = checkList.filter((item: any) => data.pidList.includes(item)), // 找出相同数据
        newList = getArrDifference(checkList, oldList); // 去掉父级ID 
      treeRef.value!.setCheckedKeys(newList, false)
    })
  } else {
    deleteRole(row.id)
  }
}
// 取出数组差异项
const getArrDifference = (arr1: any, arr2: any) => {
  return arr1.concat(arr2).filter((v: any, i: any, arr: any) => {
    return arr.indexOf(v) === arr.lastIndexOf(v);
  })
};

const save = async () => {
  let chooseAllArray = treeRef.value!.getHalfCheckedKeys(), chooseHalfArray = treeRef.value!.getCheckedKeys(false);
  data.formParams.permissions = treeRef.value!.getCheckedKeys(false) ? [...chooseAllArray, ...chooseHalfArray].join(',') : ''
  if (!formParams) return
  await formParams.value?.validate(async (valid: any, fields: any) => {
    if (valid) {
      const res: any = data.formParams.id
        ? await editGeneralRole(data.formParams)
        : await addGeneralRole(data.formParams)
      if (res.code == 1) {
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
      }
      data.isShowDetails = false
      getSearchList()
    }
  })
}

const deleteRole = (id: number) => {
  ElMessageBox.confirm('确认删除改角色?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    await deleteGeneralRole({ id: id })
    ElMessage({
      type: 'success',
      message: '操作成功'
    })
    getSearchList()
  })
    .catch(() => { })
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
  getSearchList()
}

const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}

// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const onHideDetails = () => {
  data.query = {
    page: 1,
    size: 50,
  }
  getSearchList()
}
</script>

<style scoped lang="scss">
.tree-form {
  max-height: 500px;
  overflow: auto;
}
</style>
